package com.bwie.shop.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Contract;
import com.bwie.common.domain.GlobalStatusEnum;
import com.bwie.common.domain.Shop;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.ShopEntryRequest;
import com.bwie.common.domain.request.ShopListRequest;
import com.bwie.common.domain.response.ShopListResponse;
import com.bwie.common.result.PageResult;
import com.bwie.common.utils.JwtUtils;
import com.bwie.shop.exception.ShopException;
import com.bwie.shop.mapper.ShopContractMapper;
import com.bwie.shop.mapper.ShopMapper;
import com.bwie.shop.service.ShopService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author <a href="mailto:3364114353@qq.com">liuwenliang</a>
 * @version 1.0
 * @description:
 * @date 2025/9/9 12:32
 */
@Service
public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ShopContractMapper shopContractMapper;

    @Override
    public PageResult<ShopListResponse> getShopList(ShopListRequest shopListRequest) {
        //分页
        PageHelper.startPage(shopListRequest.getPageNum(),shopListRequest.getPageSize());
        //查询数据库
        List<ShopListResponse> shopListResponse = shopMapper.getShopList(shopListRequest);
        PageInfo<ShopListResponse> shopListResponsePageInfo = new PageInfo<>(shopListResponse);
        return PageResult.toPageResult(shopListResponsePageInfo.getTotal(),shopListResponse);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void storeEntry(ShopEntryRequest shopEntryRequest) {
        //参数校验
        parameterVerification(shopEntryRequest);
        //添加店铺
        Shop shop = new Shop();
        shop.setShopName(shopEntryRequest.getShopName());
        shop.setShopDesc(shopEntryRequest.getShopDesc());
        shop.setEnterTime(DateUtil.date());
        shop.setStartTime(shopEntryRequest.getStartTime());
        shop.setEndTime(shopEntryRequest.getEndTime());
        shop.setStatus("1");
        //获取当前登录人信息
        User loginUser = getLoginUserInfo();
        shop.setUserId(loginUser.getId());
        shopMapper.storeEntry(shop);
        //添加店铺合同
        Contract contract = new Contract();
        contract.setShopId(shop.getId());
        contract.setUserId(loginUser.getId());
        contract.setStartTime(shopEntryRequest.getStartTime());
        contract.setEndTime(shopEntryRequest.getEndTime());
        contract.setStatus("1");
        contract.setOperationCategoryId(1);
        shopContractMapper.add(contract);
    }

    @Override
    public String review() {
        //获取当前登录人
        User loginUserInfo = getLoginUserInfo();
        Integer id = loginUserInfo.getId();
        //查询该用户拥有角色
        List<Integer> roleIds = shopMapper.getUserRolesByUserId(id);
        if (CollUtil.isEmpty(roleIds)) {
            throw new ShopException(GlobalStatusEnum.ROLE_IDS_IS_NULL.getLabel());
        }
        // 1代表普通职工 2代表管理员
        if (!roleIds.contains(2)) {
            throw new ShopException(GlobalStatusEnum.THIS_USER_DOES_NOT_HAVE_PERMISSION.getLabel());
        }
        return "该用户是管理员";
    }

    @Override
    public void export() {
        //查询所有店铺信息
        List<ShopListResponse> shopList = shopMapper.getShopList(new ShopListRequest());
        for (ShopListResponse shopListResponse : shopList) {
            if (shopListResponse.getStatus().equals("3")) {
                ExcelExportUtil.exportExcel(new ExportParams("店铺信息","店铺信息"),Shop.class,shopList);
            }
        }

    }

    private void parameterVerification(ShopEntryRequest shopEntryRequest) {
        //获取接收数据
        String shopName = shopEntryRequest.getShopName();
        String shopDesc = shopEntryRequest.getShopDesc();
        Integer contractNumber = shopEntryRequest.getContractNumber();
        Date startTime = shopEntryRequest.getStartTime();
        Date endTime = shopEntryRequest.getEndTime();
        //非空校验
        if (StrUtil.isBlank(shopName)) {
            throw new ShopException(GlobalStatusEnum.SHOP_NAME_IS_NULL.getLabel());
        }
        if (StrUtil.isBlank(shopDesc)) {
            throw new ShopException(GlobalStatusEnum.SHOP_DESC_IS_NULL.getLabel());
        }
        if (ObjUtil.isNull(startTime)) {
            throw new ShopException(GlobalStatusEnum.START_TIME_IS_NULL.getLabel());
        }
        if (ObjUtil.isNull(endTime)) {
            throw new ShopException(GlobalStatusEnum.END_TIME_IS_NULL.getLabel());
        }
        //店铺名称唯一性校验
        int count = shopMapper.selectOneShopNameByShopName(shopName);
        if (count > 0) {
            throw new ShopException(GlobalStatusEnum.SHOP_NAME_IS_EXIST.getLabel());
        }
    }

    public User getLoginUserInfo() {
        //获取请求头
        String token = request.getHeader(TokenConstants.TOKEN);
        //根据token解析userKey
        String userKey = JwtUtils.getUserKey(token);
        //从缓存中获取当前登录人信息
        User loginUser = (User) redisTemplate.opsForValue().get(userKey);
        return loginUser;
    }
}
